<?php
namespace Home\Controller;

use Think\Controller;
class IndexController extends CommonController {
	private $user_email = null;
	private $user_token = null;
    private $uid = null;
    private $api_status = 1;// api状态
    private $api_auth_status = 2;// api审核状态
    private $api_display = 1;// 是否显示
    private $api_enable = 1;// 是否可用
    private $apis_table = "dmp_service_apis_image";// api详情 镜像表
    private $api_auth_record_table = "dmp_service_authorization_record";// api申请授权记录表
    public static $api_goumai_title = '【 云途数据市场】API购买意向';//用户留言邮件title
    

    public function __construct(){
        parent::__construct();
        // 用户信息
        if($this->role != -1){// 游客
            $this->user_email = session('user_email');
            $this->uid = session('uid');
            $this->assign('user_email',$this->user_email);
            $this->user_token = session('user_token');
        }

        $this->assign('role',$this->role);
	}

    //所有错误跳转
    public function __call($method,$args){
        if(IS_POST){
            $this->ajaxReturn( array('status'=>404,'msg'=>'400 bad request','data'=>null));
        }else{
            $this->display();
        }
    }

	/**
	 * @desc 首页
	 */
    public function index(){
//      //读取分类信息(一级分类信息)
//      $categoryModel = D('Category');oroy($all_category_list);
//      $this->assign('category_list',array_slice($
//      $all_category_list = $categoryModel->allCategoryList();
//      //一级二级分类递归处理
//      $all_category_array = recursionWithCategall_category_array, 0,C(INDEX_CATEGORY_NUM) ) );
//      $all_json_category_string = json_encode($all_category_array);
//      $this->assign('json_category_string',$all_json_category_string);
        
        //读取轮播图信息
        $adv_list = array(
            array('title'=>'进击酒店行业','link'=>'/activity/hotel.html','src'=>'/Public/home/images/slide.jpg'),
            array('title'=>'房价网强势入驻','link'=>'http://huodong.37degree.com/s/freeew','src'=>'/Public/home/images/fangjia.jpg'),
            array('title'=>'数据征集令','link'=>'http://huodong.37degree.com/s/xenzev','src'=>'/Public/home/images/dataorder.jpg?v=201611028')
        );
        $this->assign('adv_list',$adv_list);

        $serviceRecommendModel = D('ServiceRecommend');
        // 精品数据
        $recommend = C('INDEX_RECOMMEND_NUM');
        $boutique_list = $serviceRecommendModel->recommendList($this->boutique_id,$recommend);
        // timp($boutique_list);die;
        // 推荐数据
        $recommend_list = $serviceRecommendModel->recommendList($this->recommend_id,$recommend);

        //精品店铺
        $serviceAdModel = D('ServiceAd');
        $ad_list = $serviceAdModel->ServideAdList($size=3);
        // timp($ad_list);die;
        $this->assign('ad_list',$ad_list);
        
        $this->assign('recommend_list',$recommend_list);
        $this->assign('boutique_list',$boutique_list);
        $this->assign('head_title',"云途数据市场");

    	$this->display();
    }

    public function solution(){
    	$this->assign('head_title','功能服务－云途数据市场');
    	$this->display();
    }
    
    public function solves(){
    	$this->assign('head_title','解决方案－云途数据市场');
    	$this->display();
    }
    
    // 搜索结果页
    public function search(){
    	$wd = I('get.wd',null,'urldecode,addslashes,htmlspecialchars');
        if(empty($wd)) redirect('/');

        // 搜索结果页(对服务商中文名称 like)
        $page = I('get.p',1);
        $pagesize = I('get.pagesize',20);
        
        $service_id_list = $this->_search(trim($wd));
        // timp($service_id_list);
        $ids = array_slice($service_id_list,($page-1)*$pagesize,$pagesize);
        $serviceModel = D('ServiceApisImage');// 替换为镜像表 todo
        $search_list = $serviceModel->getServiceWithEsid($ids);

        //按照搜索结果排序
        $order_search_list = $key_list = array();
        foreach ($search_list as $key=>$val){
            $key_list[$val['service_id']] = $val;
        }
        foreach ($ids as $k=>$v){
            if(array_key_exists($v, $key_list)) array_push($order_search_list,$key_list[$v]);
        }
        // timp($order_search_list);die;
        $count = count($service_id_list);

        // 推荐数据
        $serviceRecommendModel = D('ServiceRecommend');
        $recommend_list = $serviceRecommendModel->recommendList($this->boutique_id,C(INDEX_RECOMMEND_NUM));
        // 分页数据
        $page_info = $this->cpage($count,$pagesize);

        $this->assign('wd',$wd);
        $this->assign('recommend_list',$recommend_list);
        $this->assign('search_list',$order_search_list);
        $this->assign('pages',$page_info);
        $this->assign('count',$count);
        $this->assign('head_title',$wd."－搜索结果－云途数据市场");
        
        $this->display();
    }

    //获取elasticsearch搜素结果
    private function _search($keyword){
        //关键词过滤，转义 todo
        // return $this->_new_search($keyword);exit;//服务，api分开搜索

        $url = C('ES_QUERY_SERVICE_AND_API');
        $from = 0;
        $url .= "&size=".C(ES_QUERY_SIZE)."&from=".$from;

        $data = '{"query":{"bool":{"should":[';
        $data .='{"match_phrase":{"name":"'.$keyword.'"}},';
        $data .='{"match_phrase":{"desc":"'.$keyword.'"}},';
        $data .='{"match_phrase":{"provider":"'.$keyword.'"}}';
        $data .=']}}}';
        $result = dmp_es_curlrequest($url,$data,'GET');
        $result = json_decode($result,true);

        //去重
        if(isset($result['hits'])){
            $list = $result['hits']['hits'];
            // assoc_unique($list)

            $return_list_sid = array();
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    if(!in_array($v['_source']['sid'],$return_list_sid)){
                        if($v['_score'] >= C('ES_SCORE_SIZE')){
                            array_push($return_list_sid,$v['_source']['sid']);    
                        }
                        // array_push($return_list_sid,$v['_source']['sid']);
                    }
                }
            }
            // timp($return_list_sid);die;
            return $return_list_sid;
        }

        return null;

    }

    //新版搜索
    private function _new_search($keyword){
        if(empty($keyword)) return null;

        $size = C(ES_QUERY_SIZE);
        //服务搜索数据
        $service_data = $this->_essearch_with_service($keyword,$size);
        //API搜索数据
        $api_data = $this->_essearch_with_api($keyword,$size);

        $data = array();
        if(isset($service_data['hits']))  $data = array_merge($data,$service_data['hits']['hits']);
        if(isset($api_data['hits']))  $data = array_merge($data,$api_data['hits']['hits']);

        //去重
        $return_list_sid = array();
        if(!empty($data)){
            foreach ($data as $k=>$v){
                if(!in_array($v['_source']['sid'],$return_list_sid)){
                    if($v['_score'] >= C('ES_SCORE_SIZE')){
                        array_push($return_list_sid,$v['_source']['sid'] );    
                    }
                }
            }
        }
        // timp($return_list_sid);die;
        return $return_list_sid;
    }
    //es服务搜索-专项
    private function _essearch_with_service($keyword,$size=500){
        $service_name_boost = 100;
        $service_provider_boost = 80;
        $service_desc_boost = 70;

        $service_url = C('ES_QUERY_SERVICE');
        $from = 0;
        $service_url .= "&size=".$size."&from=".$from;
        
        $service_query_data = '{ "query": {"bool": {"should": [';
                $service_query_data .='{"match": {"name": 
                                    {"query": "'.$keyword.'","boost": '.$service_name_boost.' }
                                   }
                         },';

                $service_query_data .='{"match": {"desc": 
                                    {"query": "'.$keyword.'","boost": '.$service_desc_boost.'}
                                    }
                        },';
                $service_query_data .='{"match": {"provider": 
                                    {"query": "'.$keyword.'","boost": '.$service_provider_boost.'}
                                    }
                        }';              
        $service_query_data .='] } } }';
        $service_result = dmp_es_curlrequest($service_url,$service_query_data,'GET');
        $service_result = json_decode($service_result,true);

        return $service_result;
    }
    //esAPI搜索-专项
    private function _essearch_with_api($keyword,$size=500){
        $api_name_boost = 90;
        $api_provider_boost = 80;
        $api_desc_boost = 60;

        $api_url = C('ES_QUERY_API');
        $from = 0;
        $api_url .= "&size=".$size."&from=".$from;
        
        $api_query_data = '{ "query": {"bool": {"should": [';
                $api_query_data .='{"match": {"name": 
                                    {"query": "'.$keyword.'","boost": '.$api_name_boost.' }
                                   }
                         },';

                $api_query_data .='{"match": {"desc": 
                                    {"query": "'.$keyword.'","boost": '.$api_desc_boost.'}
                                    }
                        },';
                $api_query_data .='{"match": {"provider": 
                                    {"query": "'.$keyword.'","boost": '.$api_provider_boost.'}
                                    }
                        }';              
        $api_query_data .='] } } }';
        $api_result = dmp_es_curlrequest($api_url,$api_query_data,'GET');
        $api_result = json_decode($api_result,true);

        return $api_result;
    }

    //店铺搜索
    public function store(){
        $wd = I('get.wd',null,'urldecode,addslashes,htmlspecialchars');
        if(empty($wd)) redirect('/');

        // 搜索结果页(对服务商中文名称 like)
        $page = I('get.p',1);
        $pagesize = I('get.pagesize',20);
        
        $service_id_list = $this->_store_search(trim($wd));
        $ids = array_slice($service_id_list,($page-1)*$pagesize,$pagesize);

        $serviceModel = D('ServiceApisImage');// 替换为镜像表 todo
        $search_list = $serviceModel->getServiceWithEsid($ids);
        $count = count($service_id_list);

        // 分页数据
        $page_info = $this->cpage($count,$pagesize);

        $this->assign('wd',$wd);
        $this->assign('search_list',$search_list);
        $this->assign('pages',$page_info);
        $this->assign('count',$count);
        $this->assign('head_title',$wd."－服务商列表结果－云途数据市场");
        
        $this->display();    
    }

    //店铺es搜索
    private function _store_search($keyword){
        if(empty($keyword)){
            return null;
        }
        $url = C('ES_QUERY_SERVICE_AND_API');
        $from = 0;
        $url .= "&size=".C(ES_QUERY_SIZE)."&from=".$from;

        $data = '{"query":{"bool":{"should":[';
        $data .='{"match_phrase":{"provider":"'.$keyword.'"}}';
        $data .=']}}}';
        $result = dmp_es_curlrequest($url,$data,'GET');
        $result = json_decode($result,true);

        //去重
        if(isset($result['hits'])){
            $list = $result['hits']['hits'];
            // assoc_unique($list)

            $return_list_sid = array();
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    if(!in_array($v['_source']['sid'],$return_list_sid)){
                        if($v['_score'] >= C('ES_SCORE_SIZE')){
                            array_push($return_list_sid,$v['_source']['sid']);    
                        }
                        // array_push($return_list_sid,$v['_source']['sid']);
                    }
                }
            }
            // timp($return_list_sid);die;
            return $return_list_sid;
        }

        return null;

    }
    // 调试工具页（http://apistore.baidu.com/astore/toolshttpproxy?apiId=usu9zw&isAworks=1）-----普通认证用户才具有权限
    public function toolshttpproxy(){
        $api_id = I('get.api_id',null,'intval');
        $service_id = I('get.service_id',null,'intval');
        
        if(empty($api_id)) redirect('/');
        
        // 获取api信息（包含服务信息） //替换为api镜像表
        $apiModle = M();
        $sql = "select api.*,s.service_name s_service_name,s.service_name_en s_service_name_en from ".$this->apis_table." api left join dmp_services s on s.service_id=api.service_id where api.api_id=".(int)$api_id;
        $data = $apiModle->query($sql);
        // echo "<pre>";print_r($data);die;
        if(empty($data)) $info = array();
        else $info = $data[0];

        $this->assign('info',$info);
        $this->assign('host',C(DATAEX_HOST));
        $this->assign('head_title',$info["api_name"].'－API调试－云途数据市场');
        $this->display('tools'); 
        
    }

    // 点击调试时，ajax请求(*检查该用户是否注册*)
    public function ajaxToolshttpproxy(){
        // 参数获取，url拼接（获取请求方式）
        $url = I('post.url',null);
        $param_string = I('post.param_string',null);// 请求参数（字符串）
        
        //限制size大小，不超过50 AUTH_API_PAGESIZE_MAX
        if(strpos($param_string,C(AUTH_PAGESIZE_STRING)."=")!=false){
            $param_array = explode( C(AUTH_PAGESIZE_STRING)."=", $param_string);
            $other_params = explode("&", $param_array[1]);
            if($other_params[0] > C(AUTH_API_PAGESIZE_MAX)){
                $other_params[0] = C(AUTH_API_PAGESIZE_MAX);
            }
            $param_string = $param_array[0].C(AUTH_PAGESIZE_STRING)."=".implode("&", $other_params); 
        }

        $method = I('post.method',2);// 默认请求为get (0:post/get;1:post;2:get)
        if(empty($url)) $this->ajaxReturn(array('status'=>1003,'msg'=>'请求地址不正确','data'=>null));
        
        //调试时是否需要登录
        if(empty($this->uid)){
            $this->ajaxReturn(array('status'=>1005,'msg'=>'请登录','data'=>null));
        }

        //改接口是否第三方接口，是否限制调试功能？
        $api_id = I('post.api_id');
        $this->check_tools_list($api_id);

        //调试频次限制
        //todo
        if($method==2 || $method==0){
            // get形式
            try{
            	if(!empty($this->uid)){
            		// $result = curl_get_custom($url."?".$param_string,$debug=false,$this->user_email,$this->user_token);
                    $result = curl_get_custom($url."?".$param_string,$debug=true);
            	}else{
            		$result = curl_get($url."?".$param_string,$debug=true);
            	}
                
            }catch(exception $e){
                $this->ajaxReturn(array('status'=>1003,'msg'=>'网络出现问题','data'=>null));
            }
            
        }else{
            // post形式
            $params = array();
            $params_array = explode("&", $param_string);
            foreach ($params_array as $key => $value) {
                $params[$key] = $value;                
            }
            try{
            	if(!$this->uid){
            		// $result = curl_post_custom($url,$params,$debug=false,$this->user_email,$this->user_token);
                    $result = curl_post_custom($url,$params,$debug=true);
            	}else{
            		$result = curl_post($url,$param_string,$debug=true);
            	}
                
            }catch(exception $e){
                $this->ajaxReturn(array('status'=>1003,'msg'=>'网络出现问题','data'=>null));
            }
        }

        if($result && $result['status']==200){
            $this->ajaxReturn(array('status'=>200,'msg'=>'OK','data'=>$result['result']));
        }else{
            // $this->ajaxReturn(array('status'=>1004,'msg'=>'请求失败','data'=>null));
            $this->ajaxReturn(array('status'=>$result['status'],'msg'=>$result['msg'],'data'=>null));
        }

    }

    // 点击调试时，ajax请求(*检查该用户是否注册*)
    public function ajaxshttpproxytest(){
        // 参数获取，url拼接（获取请求方式）
        $email = I('post.email',null);
        $token = I('post.token',null);
        $api_url = I('post.api_url',null);

        if(empty($email) || empty($token) || empty($api_url)){
        	 $this->ajaxReturn(array('status'=>1003,'msg'=>'就三个参数你都舍不得填?','data'=>null));
        }
        try{
        	$result = curl_get_custom($api_url,$debug=false,$email,$token);
         }catch(exception $e){
           $this->ajaxReturn(array('status'=>1003,'msg'=>'网络出现问题','data'=>null));
         }

        if($result && $result['status']==200){
            $this->ajaxReturn(array('status'=>200,'msg'=>'OK','data'=>$result['result']));
        }else{
            // $this->ajaxReturn(array('status'=>1004,'msg'=>'请求失败','data'=>null));
            $this->ajaxReturn(array('status'=>$result['status'],'msg'=>$result['msg'],'data'=>null));
        }

    }

    //如果是调试受限，则返回固定数据
    private function check_tools_list($api_id=null){
        if($api_id==null) $this->ajaxReturn(array('status'=>1003,'msg'=>'缺少参数','data'=>null));

        $ToolsBlackModel = D('ToolsBlack');
        $content = $ToolsBlackModel->content($api_id);
        if($content!=false){
            $this->ajaxReturn( array('status'=>200,'msg'=>'ok','data'=>($content)) );
        }
    }

    // 详情页
    public function detail(){
        $service_id = I('get.sid',null,'intval');// 服务编号
        $api_id = I('get.api_id',null,'intval');//api编号
        $refresh = I('get.refresh',false);//是否读取缓存

        $service_list = array();
        if(!empty($service_id)){
            $key = md5("index_detail_service_list".$service_id);
            if($refresh==date("Ymd") || session( md5('37degree_redis') ) === true){//清楚缓存
                S($key,null);
                $service_list = false;
            }else{
                $service_list = S($key);
            }
            
            if($service_list===false){
                /* 查询api以及关联的服务信息 替换为api镜像表   ifnull(least(min(api.min_price),min(api.api_is_charge)),0) */
                $sql = "select s.service_id,s.service_publisher,s.service_request_heads,s.service_response_heads,s.service_name services_name,s.service_name_en services_name_en,s.service_introduction,s.service_logo,FROM_UNIXTIME((s.update_time),'%Y-%m-%d %T') service_update_time,ifnull(api.api_id,0) api_id,ifnull(api.api_name,'该服务无API') api_name,api.api_name_en,s.category_id,api.api_is_charge,api.min_price price,api.api_charge_rules,FROM_UNIXTIME ( greatest( s.update_time,api.update_time ),'%Y-%m-%d %T' ) greatest_update_time,group_concat(DISTINCT tag.name) tag_string,cate.name category_name,child_cate.name chile_cate_name,s.children_category_id,s.call_num ";
                $sql .= " from  dmp_services s left join ".$this->apis_table." api on api.service_id=s.service_id left join dmp_service_tag ser_tag on ser_tag.service_id=s.service_id left join dmp_tag tag on tag.id=ser_tag.tag_id left join dmp_category cate on cate.id=s.category_id left join dmp_category child_cate on child_cate.id=s.children_category_id where s.service_id=$service_id and api.api_status >0 group by s.service_id,api.api_name ";
                
                $serviceModel = M();
                $service_list = $serviceModel->query($sql);  
                S($key,$service_list,3600);
            }
            
            // $category_name = '';
            // if(!empty($service_list) && $service_list[0]['category_id']){
            //     $categoryModel = D('Category');
            //     $category_info = $categoryModel->getCategoryInfo($service_list[0]['category_id']);
            //     if(!empty($category_info)) $category_name = $category_info['name'];
            // }
            
            $api_id_array = $service_data = array();
            $last_update_time = $service_list[0]['greatest_update_time'];
            foreach($service_list as $k=>$v){
                array_push($api_id_array, $v['api_id']);
                $v['auth'] = 0; // 没授权
                // $v['category_name'] = $category_name;
                $service_data[$v['api_id']] = $v;
                if(strtotime($v['greatest_update_time']) > strtotime($last_update_time) ){
                    $last_update_time = $v['greatest_update_time'];
                }
            }

            $service_list = array_values($service_data);
            // echo "<pre>";print_r($service_list);die;
            unset($service_data);
        }else{
           $this->index();
        }

        $this->assign('data',$service_list);
        $this->assign('greatest_update_time',$last_update_time);
        $view_name = '服务';
        if(!empty($service_list)){
        	$view_name = $service_list[0]['services_name'];
        }
        $this->assign('head_title',$view_name.'－详情－云途数据市场');
        $this->assign('api_id',$api_id);
        $this->display();
    }

    
    public function ajaxApigm(){
    	$un = I('post.un',null);
    	$cw = I('post.cw',null);
    	$info = I('post.info',null);
    	$sp = I('post.sp',null);
    	$snc = I('post.snc',null);
    	$anc = I('post.anc',null);
    	$api_info = "服务名称: ".$snc."; API名称: ".$anc."; 服务发布商: ".$sp;
        //邮件（至王珂）

            //todo
        $email = "kew@37degree.com";
        $content = "";
        $content .= '<p>联系人：'.$un.'</p>';
        $content .= '<p>联系方式：'.$cw.' : '.$info.'</p>';
        $content .= '<p>意向购买的API：'.$api_info.'</p>';
            
        sendMail($email,self::$api_goumai_title,$content);

        $return_data = array('msg'=>'已收到您的消息，我们会尽快联系您!','status'=>200,'data'=>true);
        $this->ajaxReturn($return_data);
    }
    
    
    // 获取某api详情
    public function ajaxApiinfo(){
        $api_id = I('post.api_id',null,'intval');
        if($api_id==0){
          $this->ajaxReturn(array('status'=>200,'msg'=>'','data'=>null));
        }
        
        if(empty($api_id)) $this->ajaxReturn(array('status'=>1003,'msg'=>'缺少参数','data'=>null));

        // 市场首页都要从api镜像表中加载数据
        try{
            $apiModel = D('ServiceApisImage');
            $info = $apiModel->getInfo($api_id);
            if(!empty($info)){
                if(!empty($info['api_request_param'])){
                    $info['api_request_param'] = json_decode($info['api_request_param'],true);
                }
                if(!empty($info['api_result_field'])){
                    $info['api_result_field'] = json_decode($info['api_result_field'],true);
                }
                if(!empty($info['api_error_codes'])){
                    $info['api_error_codes'] = json_decode($info['api_error_codes'],true);
                }
                if(!empty($info['service_request_heads'])){
                    $info['service_request_heads'] = json_decode($info['service_request_heads'],true);
                }
                if(!empty($info['service_response_heads'])){
                    $info['service_response_heads'] = json_decode($info['service_response_heads'],true);
                }
            }
            $info['url_priex'] = C(DATAEX_HOST);
            
            $sample_url = "";
            foreach($info['api_request_param'] as $k=>$v){
            	$sample_url.= "&".$v['name']."=".$v['default_value'];
            }
            
            $sample_url = substr($sample_url,1);
            $sample_url = str_replace(' ','',$sample_url);
            
            $info['api_sample_url'] = $info['url_priex']."/open/".$info['service_name_en']."/".$info['api_name_en']."?".$sample_url;
            
            $this->ajaxReturn(array('status'=>200,'msg'=>'ok',data=>$info));
        }catch(exception $e){
            $this->ajaxReturn(array('status'=>1003,'msg'=>'网络出现问题',data=>null));
        }

    }


    // 用户申请授权api
    public function ajaxAuth(){
        // 是否登录
        if(empty($this->uid)) $this->ajaxReturn( array('status'=>8888,'msg'=>'您还未登录','data'=>null));
        $api_id = I('post.api_id',null,'intval');
        $service_id = I('post.service_id',null,'intval');
        $api_name = I('post.api_name',null,'intval');
        $api_name_en = I('post.api_name_en',null);
        $service_name_en = I('post.service_name_en',null);

        if(empty($api_id)) $this->ajaxReturn( array('status'=>1003,'msg'=>'此API不可用','data'=>null) );

        // 是否已经授权，授权操作（***用户是否认证***）
        if(session('37degree_auth_status')==1){
            $this->ajaxReturn( array('status'=>1003,'msg'=>'帐号认证中...','data'=>null) );
        }else if (session('37degree_auth_status')==2){
            // 已认证用户
            $authModel = M();
            $sql = "select api_id,service_id,enable,expired_time from ".$this->api_auth_record_table." where user_id=".(int)$this->uid." and api_id=".(int)$api_id;
            
            $info = $authModel->query($sql);
            if(empty($info)){
                // 新增授权
                $auth_data = array('api_id'=>$api_id,"service_id"=>$service_id,"api_name"=>$api_name,"api_name_en"=>$api_name_en,'service_name_en'=>$service_name_en);
                $this->innerAuthOption($auth_data);
            }else{
                if($info[0]['enable']==0){// 上次授权失败，重新授权
                    // 更新授权
                    $auth_data = array('api_id'=>$api_id,"service_id"=>$service_id,"api_name"=>$api_name,"api_name_en"=>$api_name_en,'service_name_en'=>$service_name_en);
                    $this->innerAuthOption($auth_data,true);
                }
               $this->ajaxReturn( array('status'=>1005,'msg'=>'已授权','data'=>null) ); 
            }

        }else{
            $this->ajaxReturn( array('status'=>9999,'msg'=>'请先实名认证','data'=>null) );
        }

    }

    // 授权操作时，更新授权记录表及与后台交互(**********************todo*****************)
    private function innerAuthOption($data,$status=false){
        if(empty($data)) $this->ajaxReturn( array('status'=>1003,'msg'=>'缺少必要参数','data'=>null) );

        $authRecordModel = M('ServiceAuthorizationRecord');
        $auth_data['user_id'] = $this->uid;
        $auth_data['api_id'] = $data['api_id'];
        $auth_data['service_id'] = $data['service_id'];
        $auth_data['api_name'] = $data['api_name'];
        $auth_data['api_name_en'] = $data['api_name_en'];
        $auth_data['email'] = $this->user_email;
        
        // 授权状态默认为不可用，只有和网管同步成功，才重置为可用
        $auth_data['enable'] = 0;
        $auth_data['expired_time'] = -1;
        $auth_data['update_time'] = $auth_data['create_time'] = time();
        if($status===true){// 更新
            $where = array('api_id'=>$data['api_id'],'user_id'=>$this->uid);
            $result = $authRecordModel->where($where)->save($auth_data);
        }else{// 新增
            $result = $authRecordModel->data($auth_data)->add();
        }
        
        // 与大后台交互（有效期需要注意）
        if($result) {
            //授权api访问
            $auth_url = C(AUTH_ADD_USER_API);
            $params = array('user'=>$this->user_email,'service'=>$data['service_name_en'],'api'=>$data['api_name_en'],'cnt_limit'=>1);//新增访问次数限制
            $auth_result = dmp_curl_post($auth_url,$params);

            $return_code_array = json_decode($auth_result['result'],true);
            if($auth_result['status']==200 && ($return_code_array['return_code']==0 || $return_code_array['return_code']=='-10014007') ){
                //限制访问次数
                $order_vary_url = C(AUTH_API_ORDER_VARY);
                $order_params = array('user'=>$this->user_email,'service'=>$data['service_name_en'],'api'=>$data['api_name_en'],'cnt'=>C(AUTH_API_ORDER_VARY_NUM) );
                $order_result = dmp_curl_post($order_vary_url,$order_params);

                $authModel = M();
                // 回写本地库中API授权为可用
                $update_sql = "update ".$this->api_auth_record_table." set enable=1 where enable=0 and user_id=".(int)$this->uid." and api_id=".(int)$data['api_id'];
                $update_result = $authModel->execute($update_sql);
                if($update_result){
                    // 授权成功
                    $this->ajaxReturn( array('status'=>200,'msg'=>'授权成功','data'=>null));
                }else{
                    // 授权的API已经同步到网关用户可以正常使用，但是市场显示的还是未授权
                }
                $this->ajaxReturn( array('status'=>200,'msg'=>'授权成功','data'=>null));
            }else{
                $this->ajaxReturn( array('status'=>1003,'msg'=>'授权失败','data'=>null) );
            }
        }

    }

    public function servicelist(){
        $page = I('get.p',1);
        $pagesize = I('get.pagesize',20);
        $serviceModel = D('ServiceApisImage');// 替换为镜像表 todo

        $data = $serviceModel->getAllService($page,$pagesize);
        //echo "<pre>";print_r($data);die;

        // 分页数据
        $page_info = $this->cpage($data['totalpage'],$pagesize);

        $this->assign('list',$data['list']);
        $this->assign('pages',$page_info);
        $this->assign('count',$data['totalpage']);
        $this->assign('head_title',"所有服务－云途数据市场");

        $this->display();
    }

    //删除改段时间使用的redis
    public function stopRedis(){
        session( md5('37degree_redis'),true);
        exit("stop redis");
    }

    //开启redis
    public function startRedis(){
        session( md5('37degree_redis'),false);
        exit("start redis");
    }

    public function testKss(){

    }

}
